'''
Created on 13/04/2010

@author: Tony Allan
'''
from Queue import Queue
import unittest
import re

from datastore.resource import Resource, ResourceDict
from runtime.spaces import Spaces, SpacesContext
from services.htmltemplate import *

SITE_TEMPLATE = """<?xml version='1.0' encoding='UTF-8'?>
    <resource
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://yarra.googlecode.com/files/resource-1.0.xsd">
        <metadata>
            <item key="datastore:resource/type" type="yarra:type/uri">
                services:type/template</item>
            <item key="dc:title" type="yarra:type/string">Site Template</item>
            <item key="dc:description" type="yarra:type/string">xxx.</item>
            <item key="yarra:version" type="yarra:type/string">0.1</item>
        </metadata>
        <content>
        <item key="content" type="yarra:type/string">
        <![CDATA[
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        <html>
          <body>
            <h1>Test</h1>
            <yarra:include comment="Body inserted here." />
          </body>
        </html>
        ]]>
        </item>
        </content>
    </resource>
    """

TEMPLATE = """<?xml version='1.0' encoding='UTF-8'?>
    <resource
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://yarra.googlecode.com/files/resource-1.0.xsd">
        <metadata>
            <item key="datastore:resource/type" type="yarra:type/uri">
                services:type/template</item>
            <item key="dc:title" type="yarra:type/string">Template</item>
            <item key="dc:description" type="yarra:type/string">xxx.</item>
            <item key="yarra:version" type="yarra:type/string">0.1</item>
        </metadata>
        <content>
            <item key="content" type="yarra:type/string">
            <![CDATA[
                <yarra:var var="a" />
                Indirect...<yarra:var var="ind" indirect="true" />
                <yarra:include uri="template:extra1" />
                <yarra:var var="y.1" />
                <yarra:var var="b.1.1.1" />
                <yarra:loop var="b" name="big loop" comment="hello">(set name "big loop") 
                  <yarra:var rel="0" />
                  <yarra:var rel="1.0" />
                  <yarra:loop rel="1" >
                    <yarra:var />
                    <yarra:var ref="big loop" rel="0" />(use name "big loop")
                  </yarra:loop>
                  <yarra:loop var="d">
                    <yarra:var var="d" />
                  </yarra:loop>
                </yarra:loop>
                <yarra:loop var="x">x</yarra:loop>
                <yarra:cond />
                <yarra:cond var="a" test="qaaa">
                  Yes...var(a)=<yarra:var var="a" />
                </yarra:cond>
                <yarra:cond var="a" ntest="qaaa">
                  Should be omitted!!!! uri(a)=<yarra:var var="a" />
                </yarra:cond>
                &#00;
                &copy;
                <?proc color='red'>
                Spaces test: <yarra:var uri="a:res2#a" />
                <yarra:loop var="r" name="dict test1">
                    dict test1: <yarra:var ref="dict test1" key="true" />=<yarra:var ref="dict test1" /></yarra:loop>
                <yarra:loop var="s" name="list test">
                    list test: <yarra:var ref="list test" key="true" />=<yarra:var ref="list test" /></yarra:loop>
                <br>
                aaa <a href="{yarra:var var='a' uri='b'}" /> <yarra:var var="a" onea="1a"> bbb {yarra:var var='a'} ccc
                ]]>
            </item>
        </content>
    </resource>
    """
    
EXTRA_TEMPLATE = """<?xml version='1.0' encoding='UTF-8'?>
    <resource
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://yarra.googlecode.com/files/resource-1.0.xsd">
        <metadata>
            <item key="datastore:resource/type" type="yarra:type/uri">
                services:type/template</item>
            <item key="dc:title" type="yarra:type/string">Site Template</item>
            <item key="dc:description" type="yarra:type/string">xxx.</item>
            <item key="yarra:version" type="yarra:type/string">0.1</item>
        </metadata>
        <content>
            <item key="content" type="yarra:type/string">
            <![CDATA[    <h1>Hello from EXTRA_TEMPLATE</h1>
                <yarra:includezzz uri="template:extra1" />]]>
            </item>
        </content>
    </resource>
    """


class Test(unittest.TestCase):

    def setUp(self):
        # We need a test spaces environment
        ns_dict = {'a': 'http://www.example.com/',
                   'b': 'http://www.dummy.com/', 
                   'template': 'http://www.dummy.com/template/'}
        spaces = Spaces()
        spaces_queue = Queue()
        self.spaces_context = SpacesContext(spaces, spaces_queue) 
        spaces.ns = ns_dict

    def tearDown(self):
        pass

    def test_general(self): 
        """[htmltemplate] Explore a range of options. (No checking for failure)"""

        # Template Resources
        template_uri = self.spaces_context.uri("template:")
        template_res = Resource(TEMPLATE)
        self.spaces_context.put(template_uri.temp1, template_res)
        site_template_res = Resource(SITE_TEMPLATE)
        self.spaces_context.put(template_uri.site1, site_template_res)
        extra_template_res = Resource(EXTRA_TEMPLATE)
        self.spaces_context.put(template_uri.extra1, extra_template_res)
    
        uri = self.spaces_context.uri("a:")
        
        res1 = Resource()
        res1.a = "qaaa"
        res1.b = [['a1', ['qaa1', 'qaa2']], ['b1', ['qbb1', 'qbb2']], 
                  ['c1', ['qcc1', 'qcc2']]]
        res1.c = "qccc"
        res1.d = "qddd"
        res1.r = {'a1':'a2','b1':'b2', 'c1':'c2', 'd1':'d2', 'e1':'e2'}
        res1.s = ['a1', 'b1', 'c1', 'd1', 'e1']
        res1.x = [{'a1':'q11','a2':'q12'}, {'a1':'q21','a2':'q22'}, 
                  {'a1':'q31','a2':'q32'}]
        res1.y = {0:'q50',1:'q51'}
        res1.z = {}
        res1.ind = "a:res2#a"
        self.spaces_context.put(uri.res1, res1)
        
        res2 = Resource()
        res2.a = "res2 var a"
        self.spaces_context.put(uri.res2, res2)
        
        x = HTMLTemplate(self.spaces_context, 
                         site_template_res, template_res, res1, 
                         verbose=False)
        #x.dump()
        #print(x.generate())
        # We don't actually test anything...
        assert True

#        base is the current URI. May be None.
#        args is a dict containing:
#            uri = Full uri or fragment.
#            var = Part of the URI passed as an argument.
#            rel = Append to current URI.
#            name = save the current uri+rel+ref in an array as this text.
#            ref = use the saved uri instead of URI.
#            indirect = take the result as a URI and return its contents.

    def check(self, html, test, value):
        s = "%s(.*)%s" % (test, test)
        e = re.search(s, html).group(1)
        self.assertEqual(e, value, 
                         "test=%s value=%s result=%s" % (test, value, e))
        
    def test_uri_options_01(self): 
        """[htmltemplate] uri construction options."""

        template = """<?xml version='1.0' encoding='UTF-8'?>
        <resource>
            <content>
                <item key="content" type="yarra:type/string">
                <![CDATA[
                test01<yarra:var uri="a:res1#a" />test01
                test02<yarra:var var="a" />test02
                test03<yarra:var var="b" rel="b" />test03
                test04<yarra:var var="b" rel="c" />test04
                test05<yarra:var var="ind" indirect="true" />test05
                <yarra:var var="a" name="xxx" />
                test06<yarra:var ref="xxx" />test06
                test07<yarra:var uri="#a" />test07
                ]]>
                </item>
            </content>
        </resource>
        """

        # Template Resources
        template_uri = self.spaces_context.uri("template:")
        template_res = Resource(template)
        self.spaces_context.put(template_uri.temp1, template_res)    
        uri = self.spaces_context.uri("a:")
        
        res1 = Resource()
        res1.a = "v-a"
        res1.b = {'b':'v-b-b', 'c':'v-b-c'}
        res1.ind = 'a:res1#a'
        self.spaces_context.put(uri.res1, res1)
        
        res2 = Resource()
        res2.a = "res2 var a"
        self.spaces_context.put(uri.res2, res2)
        
        x = HTMLTemplate(self.spaces_context, None,
                         template_res, res1, verbose=False)
        #x.dump()
        html = x.generate().strip()
        self.check(html, 'test01', 'v-a')
        self.check(html, 'test02', 'v-a')
        self.check(html, 'test03', 'v-b-b')        
        self.check(html, 'test04', 'v-b-c')        
        self.check(html, 'test05', 'v-a')
        self.check(html, 'test06', 'v-a')
        self.check(html, 'test07', 'v-a')


if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()